<template>
  <view class="maintenance-page">

    <!-- 维修类型选择 -->
    <view class="service-type-section">
      <view class="section-title">
        <u-icon name="grid-fill" size="20" color="#4facfe"></u-icon>
        <text class="title-text">选择服务类型</text>
      </view>
      <view class="type-grid">
        <view 
          v-for="(item, index) in serviceTypes" 
          :key="index"
          class="type-item"
          :class="{active: activeType === item.type}"
          @click="selectType(item.type)"
        >
          <view class="icon-box" :style="{background: item.bgColor}">
            <u-icon :name="item.icon" size="28" color="#fff"></u-icon>
          </view>
          <text class="type-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 维修表单 -->
    <view class="form-section" :class="{show: showForm}">
      <view class="form-header">
        <text class="form-title">维修申请</text>
        <text class="form-subtitle">请填写您的设备信息</text>
      </view>

      <u-form :model="form" :rules="rules" ref="uForm" label-width="150">
        <u-form-item label="设备型号" prop="model" borderBottom>
          <u-input 
            v-model="form.model" 
            placeholder="请输入您的无人机型号"
            border="none"
          ></u-input>
        </u-form-item>

        <u-form-item label="问题描述" prop="description" borderBottom>
          <u-input 
            v-model="form.description" 
            type="textarea"
            placeholder="请详细描述您遇到的问题"
            height="100"
            border="none"
          ></u-input>
        </u-form-item>

        <u-form-item label="上传照片" prop="images" borderBottom>
          <u-upload
            :fileList="form.images"
            @afterRead="afterRead"
            @delete="deleteImage"
            multiple
            maxCount="3"
            uploadText="上传故障照片"
          ></u-upload>
        </u-form-item>

        <u-form-item label="预约时间" prop="time" borderBottom @click="showTimePicker = true">
          <u-input 
            v-model="form.time" 
            placeholder="请选择预约时间"
            disabled
            disabledColor="#ffffff"
            border="none"
          ></u-input>
          <u-icon slot="right" name="calendar" size="20"></u-icon>
        </u-form-item>

        <u-form-item label="联系人" prop="contact" borderBottom>
          <u-input 
            v-model="form.contact" 
            placeholder="请输入联系人姓名"
            border="none"
          ></u-input>
        </u-form-item>

        <u-form-item label="联系电话" prop="phone" borderBottom>
          <u-input 
            v-model="form.phone" 
            placeholder="请输入联系电话"
            border="none"
          ></u-input>
        </u-form-item>
      </u-form>

      <view class="form-actions">
        <u-button 
          type="primary" 
          shape="circle" 
          @click="submitForm"
          :loading="submitting"
        >
          提交申请
        </u-button>
      </view>
    </view>

    <!-- 附近门店 -->
    <view class="shop-section" :class="{show: showShops}">
      <view class="section-header">
        <view class="title-wrapper">
          <u-icon name="map" size="20" color="#4facfe"></u-icon>
          <text class="title">附近服务点</text>
        </view>
        <view class="filter-bar">
          <u-dropdown 
            :title="sortText" 
            :options="sortOptions"
            @change="handleSortChange"
            activeColor="#4facfe"
          ></u-dropdown>
          <u-button 
            size="mini" 
            type="primary" 
            plain 
            shape="circle"
            @click="refreshLocation"
            :loading="refreshing"
          >
            <u-icon name="reload" size="16"></u-icon>
            刷新位置
          </u-button>
        </view>
      </view>

      <view class="shop-map" @click="openMap">
        <map 
          :latitude="map.latitude" 
          :longitude="map.longitude"
          :markers="map.markers"
          :scale="15"
          style="width: 100%; height: 250rpx;"
        ></map>
        <view class="map-overlay">
          <text>点击查看大地图</text>
          <u-icon name="arrow-right" size="16" color="#fff"></u-icon>
        </view>
      </view>

      <view class="shop-list">
        <view 
          v-for="(shop, index) in sortedShops" 
          :key="index"
          class="shop-card"
          @click="selectShop(shop)"
        >
          <view class="shop-info">
            <view class="shop-name">{{ shop.name }}</view>
            <view class="shop-distance">
              <u-icon name="map-fill" size="14" color="#999"></u-icon>
              {{ shop.distance }}km
            </view>
            <view class="shop-address">{{ shop.address }}</view>
            <view class="shop-services">
              <text 
                v-for="(service, i) in shop.services" 
                :key="i"
                class="service-tag"
              >
                {{ service }}
              </text>
            </view>
            <view class="shop-rating">
              <u-rate 
                :value="shop.rating" 
                size="14" 
                activeColor="#ffc107"
                readonly
              ></u-rate>
              <text class="rating-text">{{ shop.rating }}</text>
              <text class="orders-text">已服务{{ shop.orders }}次</text>
            </view>
          </view>
          <view class="shop-actions">
            <u-button 
              size="mini" 
              type="primary" 
              shape="circle"
              @click.stop="callShop(shop.phone)"
            >
              <u-icon name="phone-fill" size="14"></u-icon>
              联系
            </u-button>
            <u-button 
              size="mini" 
              type="success" 
              shape="circle"
              @click.stop="navigateToShop(shop)"
            >
              <u-icon name="map-fill" size="14"></u-icon>
              导航
            </u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 时间选择器 -->
    <u-picker 
      :show="showTimePicker" 
      mode="time" 
      :defaultTime="defaultTime"
      @confirm="timeConfirm"
      @cancel="showTimePicker = false"
    ></u-picker>

    <!-- 门店详情弹窗 -->
    <u-popup 
      :show="showShopDetail" 
      round="20" 
      mode="bottom"
      @close="showShopDetail = false"
      :closeable="true"
    >
      <view class="shop-detail">
        <view class="detail-header">
          <text class="shop-name">{{ currentShop.name }}</text>
          <text class="shop-distance">
            <u-icon name="map-fill" size="14" color="#4facfe"></u-icon>
            {{ currentShop.distance }}km
          </text>
        </view>
        
        <view class="detail-content">
          <view class="info-item">
            <u-icon name="map-fill" size="16" color="#4facfe"></u-icon>
            <text class="info-text">{{ currentShop.address }}</text>
          </view>
          
          <view class="info-item">
            <u-icon name="phone-fill" size="16" color="#4facfe"></u-icon>
            <text class="info-text">{{ currentShop.phone }}</text>
          </view>
          
          <view class="info-item">
            <u-icon name="clock-fill" size="16" color="#4facfe"></u-icon>
            <text class="info-text">营业时间: {{ currentShop.businessHours }}</text>
          </view>
          
          <view class="services-title">提供服务</view>
          <view class="service-list">
            <view 
              v-for="(service, index) in currentShop.services" 
              :key="index"
              class="service-item"
            >
              <u-icon name="checkmark-circle-fill" size="16" color="#4facfe"></u-icon>
              <text>{{ service }}</text>
            </view>
          </view>
        </view>
        
        <view class="detail-footer">
          <u-button 
            type="primary" 
            shape="circle"
            @click="callShop(currentShop.phone)"
          >
            <u-icon name="phone-fill" size="18"></u-icon>
            联系商家
          </u-button>
          <u-button 
            type="success" 
            shape="circle"
            @click="navigateToShop(currentShop)"
          >
            <u-icon name="map-fill" size="18"></u-icon>
            开始导航
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeType: '',
      showForm: false,
      showShops: false,
      showTimePicker: false,
      showShopDetail: false,
      submitting: false,
      refreshing: false,
      currentShop: {},
      defaultTime: '',
      sortText: '智能排序',
      sortOptions: [
        { label: '智能排序', value: 'smart' },
        { label: '距离最近', value: 'distance' },
        { label: '评分最高', value: 'rating' },
        { label: '服务最多', value: 'orders' }
      ],
      serviceTypes: [
        {
          type: 'repair',
          name: '故障维修',
          icon: 'error-circle',
          bgColor: 'linear-gradient(45deg, #4facfe, #00f2fe)'
        },
        {
          type: 'maintain',
          name: '定期保养',
          icon: 'error-circle',
          bgColor: 'linear-gradient(45deg, #fa709a, #fee140)'
        },
        {
          type: 'parts',
          name: '配件更换',
          icon: 'error-circle',
          bgColor: 'linear-gradient(45deg, #43e97b, #38f9d7)'
        },
        {
          type: 'detection',
          name: '验机服务',
          icon: 'eye',
          bgColor: 'linear-gradient(45deg, #a18cd1, #fbc2eb)'
        }
      ],
      form: {
        model: '',
        description: '',
        images: [],
        time: '',
        contact: '',
        phone: ''
      },
      rules: {
        model: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入问题描述', trigger: 'blur' },
          { min: 10, message: '描述不能少于10个字', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              return /^1[3-9]\d{9}$/.test(value);
            }, 
            message: '请输入正确的手机号', 
            trigger: 'blur' 
          }
        ]
      },
      map: {
        latitude: 31.2304,
        longitude: 121.4737,
        markers: []
      },
      shops: [
        {
          id: 1,
          name: '蓝天无人机维修中心',
          address: '上海市浦东新区张江高科技园区博云路123号',
          phone: '13800138000',
          distance: 1.5,
          rating: 4.8,
          orders: 256,
          businessHours: '09:00-18:00',
          services: ['故障维修', '配件更换', '设备检测', '软件升级'],
          latitude: 31.2314,
          longitude: 121.4747
        },
        {
          id: 2,
          name: '飞手之家服务站',
          address: '上海市闵行区虹桥天地2号楼101',
          phone: '13800138001',
          distance: 3.2,
          rating: 4.6,
          orders: 189,
          businessHours: '10:00-20:00',
          services: ['定期保养', '设备清洁', '电池维护'],
          latitude: 31.2294,
          longitude: 121.4727
        },
        {
          id: 3,
          name: '极飞科技授权服务中心',
          address: '上海市静安区南京西路1266号恒隆广场3楼',
          phone: '13800138002',
          distance: 5.8,
          rating: 4.9,
          orders: 312,
          businessHours: '09:30-17:30',
          services: ['专业维修', '原厂配件', '设备校准', '飞行培训'],
          latitude: 31.2334,
          longitude: 121.4757
        }
      ]
    }
  },
  computed: {
    sortedShops() {
      const shops = [...this.shops];
      switch (this.sortText) {
        case '距离最近':
          return shops.sort((a, b) => a.distance - b.distance);
        case '评分最高':
          return shops.sort((a, b) => b.rating - a.rating);
        case '服务最多':
          return shops.sort((a, b) => b.orders - a.orders);
        default:
          // 智能排序：优先距离近、评分高、服务多
          return shops.sort((a, b) => {
            const scoreA = (1 / a.distance) * 0.5 + a.rating * 0.3 + a.orders * 0.2;
            const scoreB = (1 / b.distance) * 0.5 + b.rating * 0.3 + b.orders * 0.2;
            return scoreB - scoreA;
          });
      }
    }
  },
  onLoad() {
    this.initMapMarkers();
    this.setDefaultTime();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    selectType(type) {
      this.activeType = type;
      this.showForm = true;
      this.showShops = true;
      
      // 滚动到表单区域
      setTimeout(() => {
        uni.pageScrollTo({
          selector: '.form-section',
          duration: 300
        });
      }, 100);
    },
    setDefaultTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = (now.getMinutes() + 5).toString().padStart(2, '0');
      this.defaultTime = `${hours}:${minutes}`;
    },
    timeConfirm(e) {
      this.form.time = e.time;
      this.showTimePicker = false;
    },
    afterRead(event) {
      // 模拟上传过程
      uni.showLoading({ title: '上传中...' });
      setTimeout(() => {
        const files = event.file.map(file => {
          return {
            url: file.url || 'https://picsum.photos/200/200?random=' + Math.random(),
            status: 'success'
          };
        });
        this.form.images = [...this.form.images, ...files];
        uni.hideLoading();
        uni.showToast({ title: '上传成功', icon: 'success' });
      }, 1000);
    },
    deleteImage(event) {
      this.form.images.splice(event.index, 1);
    },
    submitForm() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.submitting = true;
          // 模拟提交过程
          setTimeout(() => {
            this.submitting = false;
            uni.showToast({ 
              title: '提交成功', 
              icon: 'success',
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/maintenance/order-detail?id=123'
                  });
                }, 1500);
              }
            });
          }, 1500);
        } else {
          uni.showToast({ title: '请完善表单信息', icon: 'none' });
        }
      });
    },
    initMapMarkers() {
      this.map.markers = this.shops.map(shop => ({
        id: shop.id,
        latitude: shop.latitude,
        longitude: shop.longitude,
        iconPath: '/static/images/marker.png',
        width: 30,
        height: 30,
        callout: {
          content: shop.name,
          color: '#4facfe',
          fontSize: 14,
          borderRadius: 5,
          bgColor: '#fff',
          padding: 5,
          display: 'ALWAYS'
        }
      }));
    },
    handleSortChange(e) {
      this.sortText = e.label;
    },
    refreshLocation() {
      this.refreshing = true;
      // 模拟定位刷新
      setTimeout(() => {
        this.refreshing = false;
        uni.showToast({ title: '位置已刷新', icon: 'success' });
        
        // 随机调整距离模拟新位置
        this.shops = this.shops.map(shop => ({
          ...shop,
          distance: (Math.random() * 5 + 0.5).toFixed(1)
        }));
      }, 1000);
    },
    openMap() {
      uni.openLocation({
        latitude: this.map.latitude,
        longitude: this.map.longitude,
        scale: 15,
        name: '无人机维修点',
        address: '附近维修点位置'
      });
    },
    selectShop(shop) {
      this.currentShop = shop;
      this.showShopDetail = true;
    },
    callShop(phone) {
      uni.makePhoneCall({
        phoneNumber: phone
      });
    },
    navigateToShop(shop) {
      uni.openLocation({
        latitude: shop.latitude,
        longitude: shop.longitude,
        name: shop.name,
        address: shop.address
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.maintenance-page {
  padding-bottom: 40rpx;
  background-color: #f5f7fa;
}

/* 导航栏样式 */
.nav-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding-top: var(--status-bar-height);
  
  .nav-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 30rpx;
    height: 88rpx;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

/* 服务类型选择 */
.service-type-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title-text {
      font-size: 28rpx;
      font-weight: 600;
      margin-left: 10rpx;
      color: #333;
    }
  }
  
  .type-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    
    .type-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30rpx 0;
      border-radius: 16rpx;
      background-color: #f8fafc;
      transition: all 0.3s ease;
      
      &.active {
        background-color: rgba(79, 172, 254, 0.1);
        box-shadow: 0 0 0 2rpx #4facfe;
        
        .type-name {
          color: #4facfe;
          font-weight: 500;
        }
      }
      
      .icon-box {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 15rpx;
      }
      
      .type-name {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

/* 表单区域 */
.form-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transform: translateY(50rpx);
  opacity: 0;
  transition: all 0.5s ease;
  max-height: 0;
  overflow: hidden;
  
  &.show {
    transform: translateY(0);
    opacity: 1;
    max-height: 1000rpx;
    margin-bottom: 30rpx;
  }
  
  .form-header {
    margin-bottom: 30rpx;
    
    .form-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      display: block;
      margin-bottom: 10rpx;
    }
    
    .form-subtitle {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .form-actions {
    margin-top: 40rpx;
    
    .u-button {
      height: 80rpx;
      font-size: 28rpx;
    }
  }
}

/* 门店区域 */
.shop-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transform: translateY(50rpx);
  opacity: 0;
  transition: all 0.5s ease 0.2s;
  max-height: 0;
  overflow: hidden;
  
  &.show {
    transform: translateY(0);
    opacity: 1;
    max-height: none;
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .title-wrapper {
      display: flex;
      align-items: center;
      
      .title {
        font-size: 28rpx;
        font-weight: 600;
        margin-left: 10rpx;
        color: #333;
      }
    }
    
    .filter-bar {
      display: flex;
      align-items: center;
      gap: 15rpx;
    }
  }
  
  .shop-map {
    position: relative;
    border-radius: 16rpx;
    overflow: hidden;
    margin-bottom: 30rpx;
    
    .map-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      color: #fff;
      padding: 15rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      
      text {
        margin-right: 10rpx;
      }
    }
  }
  
  .shop-list {
    .shop-card {
      display: flex;
      justify-content: space-between;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      transition: all 0.3s ease;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:active {
        background-color: #f8fafc;
      }
      
      .shop-info {
        flex: 1;
        
        .shop-name {
          font-size: 28rpx;
          font-weight: 600;
          margin-bottom: 10rpx;
          color: #333;
        }
        
        .shop-distance {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 10rpx;
          display: flex;
          align-items: center;
        }
        
        .shop-address {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 15rpx;
        }
        
        .shop-services {
          display: flex;
          flex-wrap: wrap;
          gap: 10rpx;
          margin-bottom: 15rpx;
          
          .service-tag {
            font-size: 20rpx;
            color: #4facfe;
            background: #e6f7ff;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
          }
        }
        
        .shop-rating {
          display: flex;
          align-items: center;
          
          .rating-text {
            font-size: 24rpx;
            color: #ffc107;
            margin: 0 10rpx 0 5rpx;
            font-weight: 600;
          }
          
          .orders-text {
            font-size: 22rpx;
            color: #999;
          }
        }
      }
      
      .shop-actions {
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 15rpx;
        padding-left: 20rpx;
        
        .u-button {
          width: 120rpx;
        }
      }
    }
  }
}

/* 门店详情弹窗 */
.shop-detail {
  padding: 40rpx;
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .shop-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .shop-distance {
      font-size: 24rpx;
      color: #4facfe;
      display: flex;
      align-items: center;
    }
  }
  
  .detail-content {
    margin-bottom: 40rpx;
    
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .info-text {
        font-size: 26rpx;
        color: #666;
        margin-left: 10rpx;
      }
    }
    
    .services-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin: 30rpx 0 20rpx;
    }
    
    .service-list {
      .service-item {
        display: flex;
        align-items: center;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        color: #666;
        
        text {
          margin-left: 10rpx;
        }
      }
    }
  }
  
  .detail-footer {
    display: flex;
    gap: 20rpx;
    
    .u-button {
      flex: 1;
      height: 80rpx;
      
      .u-icon {
        margin-right: 10rpx;
      }
    }
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in-up {
  animation: fadeInUp 0.5s ease forwards;
}
</style>